﻿var net = net||{};
var wsImpl = WebSocket || MozWebSocket;
net.connect = function(ip){
	if(net.isOnline){
		alert("已经连接服务器了");
		return;
	}
	net.ws = new wsImpl('ws://'+ip+':8181/');
	net.ws.onopen = net.onopen;
	net.ws.onclose = net.onclose;
	net.ws.onmessage = net.onmessage;
	net.userId = 0;
	net.isInRoom = false;
	net.isHost = false;
	net.isOnline = false;
}
net.send = function(data){
	if(net.ws)
		net.ws.send(data);
}
net.onopen = function() {
	net.isOnline = true;
	com.log("连接服务器成功");
};
net.onclose = function() {
	net.isOnline = false;
	com.log("与服务器断开连接");
}
net.onmessage = function(e) {
	let msg = JSON.parse(e.data);
	if(msg.error){
		alert(msg.error);
		return;
	}
	switch(msg._){
		case "user":{
			net.userId = msg.user;
			com.log("你的ID是"+net.userId);
			break;
		}
		case "createRoom":{
			net.isHost = true;
			net.isInRoom = true;
			com.get("createRoomDlg").showModal();
			com.log("你创建了房间");
			break;
		}
		case "getRoom":{
			com.get("roomList").innerHTML="";
			msg.list.forEach(room => {
				let btn=document.createElement('input');
				btn.type="button";
				btn.value=room;
				btn.onclick = ()=>{
					net.send(JSON.stringify({_:"joinRoom", room:room}));
				};
				com.get("roomList").appendChild(btn);
			});
			com.get("joinRoomDlg").showModal();
			break;
		}
		case "joinRoom":{
			if(net.userId==msg.user){
				net.isInRoom = true;
				net.isHost = false;
			}
			com.log(msg.user+"进入了房间");
			if(msg.start==1){
				com.get("createRoomDlg").close();
				com.get("joinRoomDlg").close();
				play.selfReady = false;
				play.selfReady = false;
			}
			break;
		}
		case "quitRoom":{
			play.isPlay = false;
			if(msg.disband==1){
				net.isInRoom = false;
				com.log("房间已解散");
			}else{
				com.log(msg.user+"离开了房间");
				if(net.isHost)
					com.get("createRoomDlg").showModal();
			}
			break;
		}
		case "ready":{
			com.log(msg.user+"准备开始新的对局");
			if(msg.user==net.userId){
				play.selfReady = true;
			}else{
				play.targetReady = true;
			}
			if(play.selfReady && play.targetReady){
				play.init(net.isHost?1:-1);
			}
			break;
		}
		case "chat":{
			let str = "说：";
			if(msg.user==net.userId){
				str = "你"+str+msg.chat;
			}else{
				str = msg.user+str+msg.chat;
			}
			com.log(str);
			break;
		}
		case "moveChess":{
			play.moveChess(msg.key, msg.x, msg.y);
			break;
		}
		case "retract":{
			play.retract();
			break;
		}
	}
};